package com.uenpay.util.app;

/**
 * Created by PS on 2017/3/13.
 *
 * @desc activity任务栈
 */

import android.app.Activity;
import android.util.Log;

import java.util.Stack;

public class ActivityStack {

    private static Stack<Activity> activityStack;
    private static ActivityStack instance;

    private ActivityStack() {
    }

    public static ActivityStack getInstance() {
        if (instance == null) {
            instance = new ActivityStack();
        }
        return instance;
    }

    public void pop() {
        try {
            Activity activity = activityStack.lastElement();
            if (activity != null) {
                activityStack.remove(activity);
                activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void remove(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
        }
    }

    public void popTo(Activity activity) {
        if (activity != null) {
            while (true) {
                Activity lastcurrent = top();
                if (activity != top()) {
                    activityStack.remove(lastcurrent);
                    lastcurrent.finish();
                } else {
                    return;
                }
            }
        }
    }

    public Activity top() {
        try {
            return activityStack.lastElement();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void push(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack();
        }
        activityStack.add(activity);
    }

    public void popAllButBottom() {
        while (true) {
            Activity topActivity = top();
            if (topActivity != null && topActivity != activityStack.firstElement()) {
                activityStack.remove(topActivity);
                topActivity.finish();
            } else {
                return;
            }
        }
    }

    public void popAll() {
        if (activityStack != null) {
            while (true) {
                Activity activity = top();
                if (activity != null) {
                    Log.i("TAG", activity.toString());
                    activityStack.remove(activity);
                    activity.finish();
                } else {
                    return;
                }
            }
        }
    }

    public Activity bottom() {
        return activityStack.firstElement();
    }
}